package com.nsharmon.dao.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.criterion.Restrictions;

import com.google.gson.annotations.Expose;
import com.nsharmon.webapp.listeners.HibernateSessionListener;

@Entity
public class EntityObject {
	private long id;
	
	@Expose	
	private String name;
	
	public EntityObject() {
		
	}
	
	public EntityObject(String name) {
		this.name = name;
	}
	
	@Id
	@GeneratedValue(generator="increment")
	@GenericGenerator(name="increment", strategy = "increment")		
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	

	@Column(nullable=false)
	public String getName() {
		return name;
	}	
	
	public void setName(String name) {
		this.name = name;
	}	

	@Transient
	public static EntityObject getOrCreate(String name) {
		return getOrCreate(null, name);
	}
	
	@Transient
	public static EntityObject getOrCreate(Session session, String name) {
		EntityObject entity = null;
		
		boolean localSession = false;
		Transaction trx = null;
		if(session == null) {
			localSession = true;
			session = HibernateSessionListener.openSession();
			trx = session.beginTransaction();
		}
		
		try {
			entity = (EntityObject)session.createCriteria(EntityObject.class)
				.add(Restrictions.eq("name", name))
				.uniqueResult();
			
			if(entity == null) {
				entity = new EntityObject();
				entity.setName(name);
				session.save(entity);
			}
			if(localSession) {
				trx.commit();
			}
		} catch(HibernateException e) {
			if(localSession) {
				trx.rollback();
			}
			throw e;
		} finally {
			if(localSession) {
				session.close();
			}
		}
		return entity;
	}

	@Override
	@Transient
	public String toString() {
		return getName();
	}

	@Override
	@Transient	
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	@Transient	
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EntityObject other = (EntityObject) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}	
}
